const http = require('http')
const cluster = require('cluster')
if (cluster.isMaster) {
  console.log('ismaster');
  cluster.setupMaster({ //使用独立的标准输入输出
    silent: true
  })
  var worker = cluster.fork()
  worker.process.stdout.on('data', (data) => {
    console.log('来自客户端的消息:' + data);
  })
  worker.on('online', () => {
    console.log('已接收到子进程' + worker.id + '发送的消息');
  })
  // cluster.fork()
} else {
  console.log('not master');
  const server = http.createServer((rq, res) => {
    if (rq.url !== '/favicon.ico') {
      var sum = 0;
      for (var i = 0; i < 5000000; i++) {
        sum += i;
      }
      res.writeHead(200, {
        'Content-Type': 'text/html'
      });
      res.write('<head><meta charset="utf-8"/></head>');
      res.write("客户端请求在子进程" + cluster.worker.id + "中被处理。");
      res.end("sum=" + sum);
      process.stdout.write(rq.url)
    }
  }).listen(1337, 'localhost', function () {
    console.log('服务运行在子进程', server.address());
  })
}